package br.ufpb.di.ppgi.persistencia.listeners;

import javax.persistence.PostPersist;
import javax.persistence.PostUpdate;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import br.ufpb.di.ppgi.apresentacao.SiteConfiguration;
import br.ufpb.di.ppgi.negocio.modelo.contato.EmailImpl;
import br.ufpb.di.ppgi.negocio.modelo.contato.IEmail;
import br.ufpb.di.ppgi.negocio.modelo.contato.InternetIdentity;
import br.ufpb.di.ppgi.negocio.modelo.defesa.Defesa;
import br.ufpb.di.ppgi.negocio.modelo.defesa.DefesaStatus;
import br.ufpb.di.ppgi.negocio.modelo.usuario.Usuario;
import br.ufpb.di.ppgi.util.Mailer;
import br.ufpb.di.ppgi.util.PropertiesUtil;
import br.ufpb.di.ppgi.util.vraptor.ContainerRequestScoped;


public class DefesaListener {

private static final Logger LOGGER = LoggerFactory.getLogger(DefesaListener.class);
	
	private SiteConfiguration getConf() {
		return ContainerRequestScoped.instanceFor(SiteConfiguration.class);
	}
	
	private PropertiesUtil getProperties() {
		return ContainerRequestScoped.instanceFor(PropertiesUtil.class);
	}	
	
	
	private HttpServletRequest getRequest() {
		return ContainerRequestScoped.instanceFor(HttpServletRequest.class);
	}
	
	@PostPersist
	public void postPersist(Defesa defesa) {
		for (Usuario usuario : defesa.getColegiados()) {
			IEmail contato = factoryEmailInforme(usuario); 
			LOGGER.info("Enviado email para "+usuario);
			
			Mailer.getInstance().threadedSend(contato);			
		}
	}
	
	@PostUpdate
	public void postUpdate(Defesa defesa) {
		if (defesa.getStatus()  !=  DefesaStatus.PENDENTE) {
			LOGGER.info("Enviado emails de proposta homologada.");
			
			Mailer.getInstance().threadedSend(factoryEmailHomologado(defesa, getConf().getInetIdSecretario()));
			Mailer.getInstance().threadedSend(factoryEmailHomologado(defesa, getConf().getInetIdCoordenador()));
		}
	}
	
	private IEmail factoryEmailHomologado(Defesa defesa, InternetIdentity para) {
		EmailImpl email = new EmailImpl();
		
		String msg = String.format(getProperties().getString("model.email.homologacao.defesa.mensagem"),
													para.getNome(),
													defesa.getAluno()+" - "+defesa.getTitulo()+" => "+defesa.getStatus(),
													SiteConfiguration.getBase(getRequest()));
				
		email.setDe(getConf().getDe());
		email.setPara(para);
		email.setAssunto(getProperties().getString("model.email.homologacao.defesa.assunto"));
		email.setMensagemEnviada(msg);
		
		return email;
	}

	private IEmail factoryEmailInforme(Usuario usuario) {
		EmailImpl email = new EmailImpl();
		
		email.setDe(getConf().getDe());
		email.setPara(usuario.getInfoContato());
		email.setAssunto(getProperties().getString("model.informe.defesa.assunto"));
		email.setMensagemEnviada(getProperties().getString("model.informe.defesa.mensagem"));
		
		return email;
	}
	
}
